import {AfterViewInit, Component, Inject, OnDestroy, OnInit, ViewChild} from '@angular/core';
import {Message} from '../../../../../ng-tools/src/message/message';
import {Subscription} from 'rxjs';
import {BadgePipe, MessageService, ModalComponent, paginationFactory, PaginationService, ProgressBarService, Table, UnitPipe} from '../../../../../ng-tools';
import {Router} from '@angular/router';
import {DvbConfigService} from '../../../../services/api/dvb-config.service';
import {ShowFormattedDataOptions} from '../../../../../ng-tools/src/components/show-formatted-data/show-formatted-data.component';
import {DvbConfigFormatterService} from '../../../../services/formatter/dvb-config-formatter.service';
import {HttpClient, HttpParams} from '@angular/common/http';
import {finalize} from 'rxjs/internal/operators';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {AllChannelService} from '../../../../services/api/all-channel.service';
import {ChangeDvbConfigChannelComponent} from './change-dvb-config-channel/change-dvb-config-channel.component';
const dvbConfigPaginationProvider = {
  provide: PaginationService,
  useFactory: paginationFactory,
  deps: [HttpClient, DvbConfigService]
};
@Component({
  selector: 'dvb-config',
  templateUrl: './dvb-config.component.html',
  styleUrls: ['./dvb-config.component.scss'],
  providers: [
    UnitPipe,
    BadgePipe,
    dvbConfigPaginationProvider,
    DvbConfigService,
    DvbConfigFormatterService
  ]
})
export class DvbConfigComponent implements OnInit, AfterViewInit, OnDestroy, Message {
  @ViewChild('modal') private modal: ModalComponent;
  subscriptions: Subscription;
  dvbConfigPage;
  isAdvance = false;
  freqs = [];
  currentDvbConfig;
  dvbConfigForm: FormGroup;
  dvbConfigChannelForm: FormGroup;
  defaultFormValue;
  defaultDvbConfgChannelFormValue;
  dvbConfigChannelIp;
  dvbConfigChannelPort;
  isShowConfigDetail = false;
  isUpdateConfig = false;
  selectedChannel;
  currentChangeIndex = 0;
  deliverySystem = [
    {name: 'DVBT', value: 0},
    {name: 'DVBT2', value: 1},
    {name: 'DVBS', value: 2},
    {name: 'DVBS2', value: 3},
    {name: 'DVBC_ANNEX_AC', value: 4},
    {name: 'DVBC_ANNEX_B', value: 5},
    {name: 'ATSC', value: 5},
    {name: 'ISDBT', value: 7},
  ];
  codeRate = [
    {name: 'none', value: 0},
    {name: '1/2', value: 1},
    {name: '2/3', value: 2},
    {name: '3/4', value: 3},
    {name: '4/5', value: 4},
    {name: '5/6', value: 5},
    {name: '6/7', value: 6},
    {name: '7/8', value: 7},
    {name: '8/9', value: 8},
    {name: 'auto', value: 9},
  ];
  tuner = [
    {name: '0', value: 0},
    {name: '1', value: 1},
    {name: '2', value: 2},
  ];
  modulation = [
    {name: 'QPSK', value: 0},
    {name: 'QAM16', value: 1},
    {name: 'QAM32', value: 2},
    {name: 'QAM64', value: 3},
    {name: 'QAM128', value: 4},
    {name: 'QAM256', value: 5},
    {name: 'QAMAUTO', value: 6},
    {name: 'VSB8', value: 7},
    {name: 'VSB16', value: 8},
    {name: '8PSK', value: 9},
    {name: '16APSK', value: 10},
    {name: '32APSK', value: 11},
    {name: 'DQPSK', value: 12},
  ];
  currentFreqFestval = [];
  addedChannels = [];
  psiTableFilter = [
    {name: 'no', value: 0},
    {name: 'pat', value: 1},
    {name: 'pat_cat', value: 2},
  ];
  multicastIface4 = [];
  loadingOptions = {
    id: 'versionAppLoadingModal',
    message: '',
    textColor: 'teal'
  };
  dvbConfiglTable = new Table({
    headers: this.dvbFormatterService.formatter,
    buttons: [
      {
        btnClass: 'btn btn-danger btn-sm mr-1 px-1 py-0',
        iconClass: 'fa fa-fw fa-pencil-square',
        isShow: true,
        click: (e) => {
          this.isUpdateConfig = true;
          this.currentDvbConfig = e;
          this.defaultFormValue.delivery_system = e.delivery_system;
          this.defaultFormValue.freq = e.freq;
          this.defaultFormValue.srate = e.srate;
          this.defaultFormValue.coderate = e.coderate;
          this.defaultFormValue.tuner = e.tuner;
          this.defaultFormValue.modulation = e.modulation;
          this.defaultFormValue.multicast_iface4 = e.multicast_iface4;
          this.defaultFormValue.multicast_ipv4 = e.multicast_ipv4;
          this.defaultFormValue.common_port = e.common_port;
          this.defaultFormValue.multicast_ttl = e.multicast_ttl;
          this.defaultFormValue.autoconfiguration = e.autoconfiguration;
          this.defaultFormValue.multicast_auto_join = e.multicast_auto_join;
          this.defaultFormValue.ip_http = e.ip_http;
          this.defaultFormValue.dvr_buffer_size = e.dvr_buffer_size;
          this.defaultFormValue.dvr_thread = e.dvr_thread;
          this.defaultFormValue.dvr_thread_buffer_size = e.dvr_thread_buffer_size;
          this.defaultFormValue.scam_support = e.scam_support;
          this.defaultFormValue.ring_buffer_default_size = e.ring_buffer_default_size;
          this.defaultFormValue.decsa_default_delay = e.decsa_default_delay;
          this.defaultFormValue.send_default_delay = e.send_default_delay;
          this.defaultFormValue.unicast = e.unicast;
          this.defaultFormValue.port_http = '8000+%card.%number';
          this.defaultFormValue.psi_tables_filtering = e.psi_tables_filtering;
          this.defaultFormValue.autoconf_sid_list = e.autoconf_sid_list;
          this.defaultFormValue.channels = e.channels;
          this.dvbConfigForm.patchValue(this.defaultFormValue);
          this.addedChannels = e.channels;
          this.defaultDvbConfgChannelFormValue = {
            name: '',
            ip: '224.2.' + (e.id) + '.' + (this.addedChannels.length + 1) ,
            port: this.dvbConfigChannelPort,
            service_id: '',
            oscam: 1
          };
          this.dvbConfigChannelForm.patchValue(this.defaultDvbConfgChannelFormValue);
        }
      }
    ],
    rowClick: (e) => {
      this.isUpdateConfig = false;
      this.isShowConfigDetail = true;
      this.currentDvbConfig = e;
      this.defaultDvbConfgChannelFormValue = {name: '',
        ip: '224.2.' + (e.id) + '.' + (e.channels.length + 1) ,
        port: this.dvbConfigChannelPort,
        service_id: '',
        oscam: 1};
      this.dvbConfigChannelForm.patchValue(this.defaultDvbConfgChannelFormValue);
      console.log(e);
    }
  });
  breadcrumb = [
    {name: 'DVB管理', cssIcon: 'fa fa-fw fa-cubes'},
    {name: '通道管理', cssIcon: 'fa fa-fw fa-file'}
  ];
  constructor(private formBuilder: FormBuilder,
              private pagination: PaginationService,
              private router: Router,
              private channelService: AllChannelService,
              private message: MessageService,
              private dvbConfigService: DvbConfigService,
              private dvbFormatterService: DvbConfigFormatterService,
              public progress: ProgressBarService) {
    this.dvbConfigForm = this.formBuilder.group({
      delivery_system: ['', Validators.required],
      freq: ['', Validators.required],
      srate: ['', Validators.required],
      coderate: ['', Validators.required],
      tuner: ['', Validators.required],
      modulation: ['', Validators.required],
      multicast_iface4: ['', Validators.required],
      multicast_ipv4: ['', Validators.required],
      common_port: ['', Validators.required],
      multicast_ttl: ['', Validators.required],
      autoconfiguration: ['', Validators.required],
      multicast_auto_join: ['', Validators.required],
      ip_http: ['', Validators.required],
      dvr_buffer_size: ['', Validators.required],
      dvr_thread: ['', Validators.required],
      dvr_thread_buffer_size: ['', Validators.required],
      scam_support: ['', Validators.required],
      ring_buffer_default_size: ['', Validators.required],
      decsa_default_delay: ['', Validators.required],
      send_default_delay: ['', Validators.required],
      unicast: ['', Validators.required],
      port_http: ['', Validators.required],
      psi_tables_filtering: ['', Validators.required],
      autoconf_sid_list: [''],
      channels: ['', ]
    });
    this.defaultFormValue = {
      delivery_system: 4,
      freq: 474000,
      srate: 6875,
      coderate: 9,
      tuner: 0,
      modulation: 6,
      multicast_iface4: '',
      multicast_ipv4: 1,
      common_port: 5001,
      multicast_ttl: 64,
      autoconfiguration: 'full',
      multicast_auto_join: 0,
      ip_http: '0.0.0.0',
      dvr_buffer_size: 20,
      dvr_thread: 0,
      dvr_thread_buffer_size: 50000,
      scam_support: 1,
      ring_buffer_default_size: 32768,
      decsa_default_delay: 500000,
      send_default_delay: 15000000,
      unicast: 1,
      port_http: '1110+%card.%number',
      psi_tables_filtering: 0,
      autoconf_sid_list: '',
      channels: ''
    };
    this.dvbConfigChannelIp = this.defaultFormValue.ip_http;
    this.dvbConfigChannelPort = this.defaultFormValue.common_port;
    this.dvbConfigForm.patchValue(this.defaultFormValue);
    this.dvbConfigChannelForm = this.formBuilder.group({
      name: ['', Validators.required],
      ip: ['', Validators.required],
      port: ['', Validators.required],
      service_id: ['', Validators.required],
      oscam: ['', Validators.required],
    });
    this.defaultDvbConfgChannelFormValue = {name: '',
      ip: this.dvbConfigForm.value['ip_http'],
      port: this.dvbConfigForm.value['common_port'],
      service_id: '',
      oscam: 1
    };
    this.dvbConfigChannelForm.patchValue(this.defaultDvbConfgChannelFormValue);
  }

  ngOnInit() {
    this.dvbConfigService.get('' + this.dvbConfigService.urls.get_network_name).subscribe((resp) => {
      for (const item of resp.body) {
        this.multicastIface4.push({name: item, value: item});
      }
      this.defaultFormValue.multicast_iface4 = resp.body[0];
      this.dvbConfigForm.patchValue(this.defaultFormValue);
    });
    this.channelService.get('').subscribe((resp) => {
      const allChannel = resp.body;
      for (const channel of allChannel) {
        if (this.freqs.indexOf(channel.freq) === -1) {
          this.freqs.push(channel.freq);
        }
      }
      this.message.sendMessage('page load progress', this);
    });
    this.defaultFormValue.freq = this.freqs[0];
    this.dvbConfigForm.patchValue(this.defaultFormValue);
    this.channelService.get('', {
      observe: 'response',
      params: new HttpParams().set('freq', this.dvbConfigForm.value['freq'])
    }).subscribe((resp) => {
      this.currentFreqFestval = resp.body;
    });
    this.pagination.setPageParam(1, 12);
    this.pagination.init(this.dvbConfiglTable.options.headers);
    this.dvbConfigPage = this.pagination;
    /** 绑定事件 */
    this.pagination.dataLoadSubscriber$.pipe(finalize(() => {
      this.message.sendMessage('page load progress', this);
    })).subscribe({
      error: error => {
        console.log(error);
      }
    });
  }

  advanceConfig() {
    this.isAdvance = !this.isAdvance;
  }
  ngAfterViewInit(): void {
    this.message.sendMessage('breadcrumb changed', this, this.breadcrumb);
    this.message.sendMessage('page load progress', this, '300ms');
  }
  selectCurrentFreqFestival() {
    this.channelService.get('', {
      observe: 'response',
      params: new HttpParams().set('freq', this.dvbConfigForm.value['freq'])
    }).subscribe((resp) => {
      this.currentFreqFestval = resp.body;
      console.log(this.currentFreqFestval);
      this.dvbConfigForm.value.srate = this.currentFreqFestval[0].srate;
      for (const item of this.codeRate) {
         if (this.currentFreqFestval[0].coderate === item.name) {
           this.dvbConfigForm.value.coderate = item.value;
         }
      }
      for (const sys of this.deliverySystem) {
        if (sys.name === this.currentFreqFestval[0].name) {
          this.dvbConfigForm.value.delivery_system = sys.value;
        }
      }
      console.log(this.dvbConfigForm.value);
      this.dvbConfigForm.patchValue(this.dvbConfigForm.value);
    });
  }

  addToConfigChannels() {
    if (this.dvbConfigChannelForm.valid) {
      if (this.addedChannels.indexOf(this.dvbConfigChannelForm.value) !== -1) {
        alert('已存在该节目!');
      } else {
      this.addedChannels.push(this.dvbConfigChannelForm.value);
        this.defaultDvbConfgChannelFormValue = {
          name: '',
          ip: '224.2.' + (this.currentDvbConfig.id) + '.' + (this.addedChannels.length + 1) ,
          port: this.dvbConfigChannelPort,
          service_id: '',
          oscam: 1};
        this.dvbConfigChannelForm.patchValue(this.defaultDvbConfgChannelFormValue);
      }
    }
  }
  showChangeDvbConfigChannel(channel) {
    this.currentChangeIndex = this.addedChannels.indexOf(channel);
    this.modal.show({
      title: '修改节目',
      cssIcon: 'fa fa-fw fa-plus-circle',
      dynamicComponent: {
        component: ChangeDvbConfigChannelComponent,
        data: channel,
        events: {
          success: (data) => {
            this.modal.hide();
            this.addedChannels[this.currentChangeIndex] = data;
          }
        }
      },
      data: null
    });
  }
  setDvbConfigChannelItemValue() {
    this.dvbConfigChannelIp = this.dvbConfigForm.value.ip_http;
    this.dvbConfigChannelPort = this.dvbConfigForm.value.common_port;
  }
  setChannelData(value) {
    this.selectedChannel = value;
    this.defaultDvbConfgChannelFormValue.name = value.name;
    this.defaultDvbConfgChannelFormValue.service_id = value.sid;
    this.defaultDvbConfgChannelFormValue = {
      name: value.name,
      ip: '224.2.' + (this.currentDvbConfig.id) + '.' + (this.addedChannels.length + 1) ,
      port: this.dvbConfigChannelPort,
      service_id: value.sid,
      oscam: 1};
    this.dvbConfigChannelForm.patchValue(this.defaultDvbConfgChannelFormValue);
  }
  deleteChannel(value) {
    this.addedChannels.splice(this.addedChannels.indexOf(value), 1);
    this.defaultDvbConfgChannelFormValue = {name: '',
      ip: '224.2.' + (this.currentDvbConfig.id) + '.' + (this.addedChannels.length + 1) ,
      port: this.dvbConfigChannelPort,
      service_id: '',
      oscam: 1};
    this.dvbConfigChannelForm.patchValue(this.defaultDvbConfgChannelFormValue);
  }
  saveConfig() {
    if (this.dvbConfigForm.valid) {
      const autoconfSidList = [];
      for (const channel of this.addedChannels) {
        autoconfSidList.push(channel.service_id);
      }
      this.dvbConfigForm.value['autoconf_sid_list'] = autoconfSidList;
      this.dvbConfigForm.value['channels'] = this.addedChannels;
      if (this.currentDvbConfig.status === 0) {
        this.dvbConfigForm.value['status'] = 1;
      } else {
        this.dvbConfigForm.value['status'] = this.currentDvbConfig.status;
      }
      console.log(this.dvbConfigForm.value);
      const url = this.currentDvbConfig.id + '/' + this.dvbConfigService.urls.updata_dvb_config;
      this.dvbConfigService.post(url, this.dvbConfigForm.value).subscribe((resp) => {
        this.isUpdateConfig = false;
        this.isShowConfigDetail = true;
        this.pagination.refresh();
      });
    }
  }
  ngOnDestroy(): void {
  }

}
